import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_give/utils/LogUtils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:oktoast/oktoast.dart';
import '../../repository/api.dart';
import '../../sample/configure/constants.dart';
import '../../theme.dart';
import '../../utils/encrypt.dart';
import '../../utils/persistent_storage.dart';
import 'auth_vm.dart';


/// 注册页面
class RegisterPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _RegisterPageState();
  }
}

class _RegisterPageState extends State<RegisterPage> {
  AuthViewModel viewModel = AuthViewModel();

  // final TextEditingController _account =
  //     TextEditingController(text: "15220730439");
  // final TextEditingController _username = TextEditingController(text: "测试");
  //
  // final TextEditingController _password =
  //     TextEditingController(text: "5201314qaz.");
  // final TextEditingController _savepaddword =
  //     TextEditingController(text: "5201314qaz.");

  final TextEditingController _account =
  TextEditingController(text: "");
  final TextEditingController _username = TextEditingController(text: "");

  final TextEditingController _password =
  TextEditingController(text: "");
  final TextEditingController _savepaddword =
  TextEditingController(text: "");

  // 用户隐私协议
  bool _isAgreementChecked = false;

  bool _isCounting = false;
  int _seconds = 60;

  @override
  void initState() {
    super.initState();
    _username.addListener(_onTextChanged);
    _account.addListener(_onTextChanged);
    _password.addListener(_onTextChanged);
    _savepaddword.addListener(_onTextChanged);
    _loadAgreementStatus();
  }

  @override
  void dispose() {
    _username.removeListener(_onTextChanged);
    _account.removeListener(_onTextChanged);
    _password.removeListener(_onTextChanged);
    _savepaddword.removeListener(_onTextChanged);
    super.dispose();
  }

  void _onTextChanged() {
    setState(() {
    });
  }

  // 注册
  void _register() async {
    // LogUtils.w(_username.text);

    // 正则表达式验证11位手机号
    RegExp phoneRegex = RegExp(r'^1[3-9]\d{9}$');

    if (_account.text.isEmpty) {
      showToast("请输入手机号");
      return;
    } else if (!phoneRegex.hasMatch(_account.text)) {
      showToast("请输入有效的11位手机号");
      return;
    }

    // 校验判断
    if (_username.text.isEmpty) {
      showToast("请输入验证码");
      return;
    }

    // 正则表达式：至少包含一个数字和一个字母，且长度大于6位
    final RegExp usernameRegex =
    // RegExp(r'^(?=.*[A-Za-z])(?=.*\d)(?=.*[\W_])[A-Za-z\d\W_]{7,}$');
    RegExp(r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{7,}$');

    if (!usernameRegex.hasMatch(_password.text)) {
      showToast("密码必须大于6位，且包含数字和字母");
      return;
    }

    if (!usernameRegex.hasMatch(_savepaddword.text)) {
      showToast("密码必须大于6位，且包含数字和字母");
      return;
    }

    if (_password.text != _savepaddword.text) {
      showToast("两次密码必须一样");
      return;
    }

    // 验证验证码是否正确
    // bool swticher = await Api.instance.usergetsave(phone: _account.text,code: _username.text);
    // if (!swticher) {
    //   showToast("验证码不正确");
    //   return;
    // }

    // 密码加密
    String passwordss = AESEncryption.encrypt(_password.text);

    LogUtils.w(passwordss);

    viewModel.setRegisterInfo(
        accout: _account.text,
        username: _username.text,
        password: passwordss,
        rePassword: _savepaddword.text);
    viewModel.register().then((value) => {
          LogUtils.w("注册之后${value}"),
          // LoginPageState.globalKeyfour.currentState?.reloadData(),

          // setState(() {
          //   SharedPreferencesUtil.instance.setString(
          //       SampleConstants.storageKeyLoginAccount, _account.text);
          //   showToast("注册成功");
          // }),

         if (value == true) {
           Navigator.of(context).pop(),
           showToast("注册成功"),
         }
        });
  }

  // 用户隐私协议
  void _loadAgreementStatus() async {
    final protocolAndPrivacy = await SharedPreferencesUtil.instance
        .getBool(SampleConstants.storageKeyAgreementPrivacyStatus);
    setState(() {
      _isAgreementChecked = protocolAndPrivacy == true;
    });
  }

  // 发送验证码
  void _getcode () async {
    String data = await Api.instance.userregistergetcode(phone: _account.text);
    LogUtils.w(data);
    if (data.isEmpty) {
      showToast("验证码发送成功");
    }
  }

  void _startCountdown() async {
    if (_isCounting) return;

    // 正则表达式验证11位手机号
    RegExp phoneRegex = RegExp(r'^1[3-9]\d{9}$');

    if (_account.text.isEmpty) {
      showToast("请输入手机号");
      return;
    } else if (!phoneRegex.hasMatch(_account.text)) {
      showToast("请输入有效的11位手机号");
      return;
    }

    setState(() {
      _isCounting = true;
    });

    // 打印发送验证码
    print("发送验证码11");
    _getcode ();


    Future.doWhile(() async {
      await Future.delayed(Duration(seconds: 1));

      setState(() {
        if (_seconds > 0) {
          _seconds--;
        } else {
          _isCounting = false;
          _seconds = 60;
        }
      });
      return _isCounting;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          padding: EdgeInsets.only(left: 30, right: 30),
          alignment: Alignment.center,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(height: 40),
              Container(
                alignment: Alignment.centerLeft, // 设置容器内容左对齐
                child: Text(
                  "注册账号",
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.w600,
                    fontFamily: "PingFang SC, PingFang SC",
                  ),
                ),
              ),
              SizedBox(height: 30),
              TextField(
                controller: _account,
                decoration: InputDecoration(
                  hintText: "请输入账号",
                  border: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Color(0xFFCCCCCC),
                    ),
                  ),
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Color(0xFF00c888),
                    ),
                  ),
                  suffixIcon: _account.text.isNotEmpty
                      ? IconButton(
                    icon: Icon(Icons.clear),
                    onPressed: () {
                      setState(() {
                        _account.clear();
                      });
                    },
                  )
                      : null,
                ),
                cursorColor: Color(0xFF00c888),
              ),
              Spacer(),
              // 手机号输入框
              Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: _username,
                      decoration: InputDecoration(
                        hintText: "请输入验证码",
                        border: UnderlineInputBorder(
                          borderSide: BorderSide(
                            color: Color(0xFFCCCCCC), // 默认边框颜色
                          ),
                        ),
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(
                            color: Color(0xFF00c888), // 获得焦点时的边框颜色
                          ),
                        ),
                        suffixIcon: _username.text.isNotEmpty // 当输入框有值时显示叉号
                            ? IconButton(
                                icon: Icon(Icons.clear),
                                onPressed: () {
                                  setState(() {
                                    _username.clear(); // 清空输入框的值
                                  });
                                },
                              )
                            : null,
                      ),
                      cursorColor: Color(0xFF00c888), // 设置光标颜色
                    ),
                  ),
                  SizedBox(width: 10),
                  ElevatedButton(
                    onPressed: _isCounting ? null : _startCountdown,
                    child: Text(
                      _isCounting ? "$_seconds 秒后重试" : "获取验证码",
                      style: TextStyle(color: Color(0xFF00C888)),
                    ),
                  ),
                ],
              ),
              // TextField(
              //   controller: _username,
              //   decoration: InputDecoration(
              //     hintText: "请输入昵称",
              //     border: UnderlineInputBorder(
              //       borderSide: BorderSide(
              //         color: Color(0xFFCCCCCC),
              //       ),
              //     ),
              //     focusedBorder: UnderlineInputBorder(
              //       borderSide: BorderSide(
              //         color: Color(0xFF00c888),
              //       ),
              //     ),
              //     suffixIcon: _username.text.isNotEmpty
              //         ? IconButton(
              //             icon: Icon(Icons.clear),
              //             onPressed: () {
              //               setState(() {
              //                 _username.clear();
              //               });
              //             },
              //           )
              //         : null,
              //   ),
              //   cursorColor: Color(0xFF00c888),
              // ),
              Spacer(),
              // 验证码输入框


              TextField(
                controller: _password,
                decoration: InputDecoration(
                  hintText: "请输入密码",
                  border: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Color(0xFFCCCCCC),
                    ),
                  ),
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Color(0xFF00c888),
                    ),
                  ),
                  suffixIcon: _password.text.isNotEmpty // 当输入框有值时显示叉按钮
                      ? IconButton(
                          icon: Icon(Icons.clear),
                          onPressed: () {
                            _password.clear(); // 清空输入框的值
                          },
                        )
                      : null,
                ),
                cursorColor: Color(0xFF00c888),
              ),
              SizedBox(height: 8),

              Transform.translate(
                offset: Offset(-32.sp, 0), // 向左偏移 15
                child: Text(
                  "密码必须包含数字和字母，且长度超过8位",
                  style: TextStyle(
                    fontSize: 14,
                    color: Color(0xFFcccccc),
                  ),
                ),
              ),
              const SizedBox(height: 15),
              TextField(
                controller: _savepaddword,
                decoration: InputDecoration(
                  hintText: "请再次输入密码",
                  border: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Color(0xFFCCCCCC),
                    ),
                  ),
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: Color(0xFF00c888),
                    ),
                  ),
                  suffixIcon: _savepaddword.text.isNotEmpty // 当输入框有值时显示叉号
                      ? IconButton(
                          icon: Icon(Icons.clear),
                          onPressed: () {
                            _savepaddword.clear(); // 清空输入框的值
                          },
                        )
                      : null,
                ),
                cursorColor: Color(0xFF00c888),
              ),
              const SizedBox(height: 10),
              _buildAgreementCheckbox(),
              const SizedBox(height: 15),
              // 注册
              _buildRegionButton(),
              Spacer(),
              Spacer(),
              Spacer(),
              Spacer(),
              Spacer(),
              Spacer(),
              Spacer(),
            ],
          ),
        ),
      ),
    );
  }

  // 用户隐私协议
  Widget _buildAgreementCheckbox() {
    return Center(
      child: Row(
        children: [
          Transform.translate(
            offset: const Offset(-15, 0), // 向左移动24像素，可以根据实际情况调整
            child: Theme(
              data: ThemeData(
                unselectedWidgetColor: SampleThemeConfigure.colorTextHint,
              ),
              child: Checkbox(
                value: _isAgreementChecked,
                onChanged: (bool? newValue) {
                  setState(() {
                    _isAgreementChecked = newValue ?? false;
                  });
                  SharedPreferencesUtil.instance.setBool(
                      SampleConstants.storageKeyAgreementPrivacyStatus,
                      newValue ?? false);
                },
                checkColor: Colors.white,
                activeColor: SampleThemeConfigure.colorPrimary,
              ),
            ),
          ),
          Transform.translate(
            offset: const Offset(-20, 0), // 文字向左偏移15像素
            child: const Text(
              "我已阅读并同意",
              style: TextStyle(
                  color: SampleThemeConfigure.colorTextSub, fontSize: 12),
            ),
          ),
          Transform.translate(
            offset: const Offset(-15, 0), // 文字向左偏移15像素
            child: InkWell(
              onTap: () {
                // Navigator.push(
                //   context,
                //   MaterialPageRoute(builder: (context) => UserProtocolPage()),
                // );
              },
              child: const Text(
                '《用户协议》',
                style: TextStyle(color: Color(0xFF00C888), fontSize: 12),
              ),
            ),
          ),
          Transform.translate(
            offset: const Offset(-15, 0), // 文字向左偏移15像素
            child: const Text(
              "与",
              style: TextStyle(
                  color: SampleThemeConfigure.colorTextSub, fontSize: 12),
            ),
          ),
          Transform.translate(
            offset: const Offset(-15, 0), // 文字向左偏移15像素
            child: InkWell(
              onTap: () {
                // Navigator.push(
                //   context,
                //   MaterialPageRoute(builder: (context) => PrivacyPage()),
                // );
              },
              child: const Text(
                '《隐私政策》',
                style: TextStyle(color: Color(0xFF00C888), fontSize: 12),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 注册
  Widget _buildRegionButton() {
    return SizedBox(
      width: 400, // 设置按钮宽度为400
      height: 45, // 设置按钮高度为40
      child: ElevatedButton(
        onPressed: _register,
        style: ElevatedButton.styleFrom(
          backgroundColor: SampleThemeConfigure.colorPrimary,
          foregroundColor: SampleThemeConfigure.colorForeground,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 80),
          // 调整水平内边距
          elevation: 0,
          shadowColor: Colors.transparent,
        ),
        child: const Text(
          '注 册',
          style: TextStyle(fontSize: 18),
          textAlign: TextAlign.center, // 确保文字居中
        ),
      ),
    );
  }
}
